/*******************************************************************************
 * Copyright (c) 2013-2017 Lorenzo Bettini.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Lorenzo Bettini - Initial contribution and API
 *******************************************************************************/


/*
 * generated by Xtext
 */
package org.eclipse.xsemantics.dsl.tests.generator;

import org.eclipse.xsemantics.dsl.generator.XsemanticsOutputConfigurationProvider;

import java.io.File;
import java.util.List;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.xtext.generator.IGenerator;
import org.eclipse.xtext.generator.JavaIoFileSystemAccess;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.validation.CheckMode;
import org.eclipse.xtext.validation.IResourceValidator;
import org.eclipse.xtext.validation.Issue;

import com.google.inject.Inject;

public class GeneratorForTests {
	
	@Inject
	private IResourceValidator validator;
	
	@Inject
	private IGenerator generator;
	
	@Inject 
	private JavaIoFileSystemAccess fileAccess;
	
	protected String outputPath = XsemanticsOutputConfigurationProvider.XSEMANTICS_GEN;

	public String getOutputPath() {
		return outputPath;
	}

	public void setOutputPath(String outputPath) {
		this.outputPath = outputPath;
	}

	public List<Issue> runGenerator(String string, ResourceSet set) {
		// load the resource
		Resource resource = set.getResource(URI.createURI(string), true);

		// validate the resource
		List<Issue> issues = validator.validate(resource, CheckMode.ALL,
				CancelIndicator.NullImpl);
		if (!issues.isEmpty()) {
			for (Issue issue : issues) {
				System.err.println(issue);
			}
			if (GeneratorUtils.hasErrors(issues))
				return issues;
		}

		fileAccess.setOutputPath(outputPath);
		generator.doGenerate(resource, fileAccess);

		System.out.println("Code generation finished.");

		return issues;
	}
	
	/**
	 * Cleans all contents of the output folder (all files and directories) but
	 * not the output folder itself
	 */
	public void cleanOutputFolder() {
		String folderToClean = getOutputPath();
		File f = new File(folderToClean);
		if (f.exists()) {
			cleanAllFilesAndDirectories(f, false);
		}
	}

	protected void cleanAllFilesAndDirectories(File parentFolder,
			boolean cleanParentFolder) {
		final File[] contents = parentFolder.listFiles();
		for (int j = 0; contents != null && j < contents.length; j++) {
			final File file = contents[j];
			if (file.isDirectory()) {
				cleanAllFilesAndDirectories(file, true);
			} else {
				file.delete();
			}
		}
		if (cleanParentFolder)
			parentFolder.delete();
	}
}
